package com.xudm.cdg.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录拦截器
 *
 * @author xudm
 */
//@Component
@Slf4j
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod hm = null;
        if (handler instanceof HandlerMethod) {
            hm = (HandlerMethod) handler;
        }
        if (hm == null) {
            return true;
        }
        //校验访客信息
        String visitorId = LoginUtil.getLoginId();
        if (visitorId == null) {
            throw new RuntimeException("访客信息不存在，请重新登录");
        }
        log.info("当前访客:{}", visitorId);
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        LoginUtil.removeVisitorId();
    }
}
